import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../large_data/pic'
img_name = 'opencv_logo.png'
# img_name = 'IMG_20200819_124310.jpg'
# img_name = 'HSV.jpg'
img_path1 = os.path.join(img_dir, img_name)

spr = 1
spc = 2
spn = 0
plt.figure(figsize=[12, 6])

sep('load')
img = cv.imread(img_path1, cv.IMREAD_COLOR)
print('original shape', img.shape)
my_show_img(img, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('bgr => hsv')
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)

sep('analyze color')
tgt_color = np.uint8([[[0, 0, 255]]])
print('tgt color: bgr: ', tgt_color)
hsv_color = cv.cvtColor(tgt_color, cv.COLOR_BGR2HSV)
print('hsv: ', hsv_color)

sep('get mask')
hsv_h = hsv_color[0, 0, 0]
range1, range2 = select_color(hsv_h, 10, 10)

mask = None
for range in (range1, range2):
    print(range)
    if range is None:
        continue
    a, b = range
    lower_border = np.array([a, 100, 100], dtype=np.uint8)
    upper_border = np.array([b, 255, 255], dtype=np.uint8)
    m = cv.inRange(hsv, lower_border, upper_border)
    if mask is None:
        mask = m
    else:
        mask = cv.bitwise_or(mask, m)
print(f'mask unique: {np.unique(mask)}')
my_show_img(mask, 'mask', None, cmap='gray')
